#!/usr/bin/python2
# -*- coding: utf-8 -*-

from PySide import QtNetwork, QtCore
import base64
from .. mol import Mol2pic


def uri_b64decode(s):
    return base64.urlsafe_b64decode(s + '=' * (4 - len(s) % 4))

class MyreqReply(QtNetwork.QNetworkReply):
    '''Persional protocol, mainly for svg generation on the fly'''
    def __init__(self, parent, url, operation):
        QtNetwork.QNetworkReply.__init__(self, parent)
        self.offset = 0
        self.mime = "image/svg+xml"
        self.content = self.handler(url)
        self.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, self.mime)
        self.setHeader(QtNetwork.QNetworkRequest.ContentLengthHeader, len(self.content))
        QtCore.QTimer.singleShot(0, self, QtCore.SIGNAL("readyRead()"))
        QtCore.QTimer.singleShot(0, self, QtCore.SIGNAL("finished()"))
        self.open(self.ReadOnly | self.Unbuffered)
        self.setUrl(url)

    def abort(self):
        pass

    def handler(self, url):
        l = url.toString().split('?')
        gen_img = ''
        mol = ''
        width, height = 600, 600
        args = {}
        if len(l) >= 2:
            args = dict([i.split('=') for i in l[1].split('&')])

        if args.has_key('do'):
            if args['do'] == 'svg':
                gen_img = 'svg'
                self.mime = 'image/svg+xml'
            elif args['do'] == 'png':
                gen_img = 'png'
                self.mime = 'image/png'
            else:
                self.mime = 'text/html'
        if args.has_key('mol'):
            mol = uri_b64decode(args['mol'].encode('utf8'))

        if args.has_key('width') and args.has_key('height'):
            width, height = args['width'], args['height']

        if gen_img and mol:
            return Mol2pic(mol, width, height).to_pic(gen_img)

    def bytesAvailable(self):
        return len(self.content) - self.offset

    def isSequential(self):
        return True

    def readData(self, maxSize):
        if self.content and self.offset < len(self.content):
            end = min(self.offset + maxSize, len(self.content))
            data = self.content[self.offset:end]
            self.offset = end
            return data

class NetworkAccessManager(QtNetwork.QNetworkAccessManager):
    def __init__(self, old_manager):
        QtNetwork.QNetworkAccessManager.__init__(self)
        self.old_manager = old_manager
        self.setCache(old_manager.cache())
        self.setCookieJar(old_manager.cookieJar())
        self.setProxy(old_manager.proxy())
        self.setProxyFactory(old_manager.proxyFactory())

    def createRequest(self, operation, request, data):
        if request.url().scheme() != "myreq":
            return QtNetwork.QNetworkAccessManager.createRequest(self, operation, request, data)

        if operation == self.GetOperation:
            reply = MyreqReply(self, request.url(), self.GetOperation)
            return reply
        else:
            return QtNetwork.QNetworkAccessManager.createRequest(self, operation, request, data)

if __name__ == "__main__":
    from PySide import QtWebKit, QtGui, QtCore
    import sys, os
    class Viewer(QtWebKit.QWebView):
        def __init__(self, sdfviewer_url):
            QtWebKit.QWebView.__init__(self)

            old_manager = self.page().networkAccessManager()
            new_manager = NetworkAccessManager(old_manager)
            self.page().setNetworkAccessManager(new_manager)
            self.load(QtCore.QUrl(sdfviewer_url))
            #print self.page().mainFrame().toPlainText()
    app = QtGui.QApplication(sys.argv)
    v = Viewer("test.html")
    v.show()
    sys.exit(app.exec_())

